package com.hdax.shiro01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

import java.util.Arrays;
import java.util.Scanner;

public class MainApplication {
    public static void main(String[] args) {
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //认证主体
        Subject subject = SecurityUtils.getSubject();
        //登录
        Scanner input = new Scanner(System.in);
        System.out.println("请输入登录用户名：");
        String username = "zhangsan";
        System.out.println("请输入登录密码;");
        String password = "123456";
        //令牌 - 车票
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
            //认证
            System.out.println("登录成功！");
            System.out.println("是否认证成功："+subject.isAuthenticated());

            //授权
            //能不能收发消息
//            System.out.println(subject.hasAllRoles(Arrays.asList("群主", "管理员")));
//            boolean[] bools = subject.hasRoles(Arrays.asList("群主", "群成员"));
//            //是否是管理员
//            System.out.println("是否是管理员："+subject.hasRole("管理员"));

            //是否是群主
            System.out.println("是否群主："+subject.hasRole("群主"));
            System.out.println("能不能\"转让群\":"+subject.isPermitted("转让群"));
            System.out.println("能不能\"收发消息\":"+subject.isPermitted("收发消息"));

//            for (boolean b : bools){
//                System.out.println(b);
//            }
            //退出登录
            subject.logout();
            System.out.println("是否已经退出："+!(subject.isAuthenticated()));
        }catch (IncorrectCredentialsException e){
            System.out.println("登录失败，密码不正确");
        }catch (UnknownAccountException e){
            System.out.println("登录失败，账户不存在");
        }












    }
}
